<template>
<section class="content" id="content">
  <lq-form :form="form" :rules="rules" ref="addMHBIFormRef">
    <template #footer>
        <div style="padding-bottom: 10px;" >
          <el-button type="primary" @click="handleSubmit" v-if="materialOptCase.operaCase !== 'view'">提交</el-button>
          <el-button type="default" @click="()=> materialOptCase.closeDialog()">取消</el-button>
        </div>
    </template>
  </lq-form>
</section>
</template>

<script setup lang="ts">
/**
 * 全局方法引入
 */
const global = getCurrentInstance().appContext.config.globalProperties;

import {
  ref,
  reactive,
  onMounted,
  toValue,
  defineExpose,
  defineEmits,
  getCurrentInstance,
  inject,
  nextTick
} from "vue";
import {FormInstance, FormRules} from "element-plus";

import {ElMessage, ElMessageBox} from "element-plus";
import LqForm from "@/pages/components/LqForm.vue";
import {editKey, editMaterialKey} from '../../components/keys.js';

//=========== inject ============
const optCase = inject(editKey)
const materialOptCase = inject(editMaterialKey)


const emit = defineEmits<{
  (e: 'flush', value: Object): void
}>()

// 表单数据结构
const form = ref({
  innerAttrs: {
    size: 'default',
    labelPosition: 'right',
    labelWidth: 160,
    disabled: false,
  },
  model: {
    id: '',
    name: '',
    safetyNo: '',
    isToxic: '',
    device: '',
    onlineStore: '',
    critValue: '',
    betaValue: '',
    remark: ''
  },
  formItems: [
    {type: 'input', label: '危险化学品名称: ', prop: 'name', span: 12, maxlength: 30, placeholder: '危险化学品名称'},
    {type: 'blank', span: 12, },
    {type: 'input', label: '危规号: ', prop: 'safetyNo', span: 12, placeholder: '危规号'},
    {type: 'radio', label: '是否剧毒化学品: ', prop: 'isToxic', options: [{label: '是', value: true},{label: '否', value: false}], span: 12, placeholder: '请选择是否是剧毒化学品'},
    {type: 'input', label: '所处装置（或区域）: ', prop: 'device', span: 24, placeholder: '所处装置（或区域）'},
    {type: 'number', label: '在线存在量（吨）: ', prop: 'onlineStore', span: 12, placeholder: '在线存在量（吨）', },
    {type: 'number', label: '临界值（吨）: ', prop: 'critValue', span: 12, placeholder: '临界值（吨）'},
    {type: 'input', label: '校正系数: ', prop: 'betaValue', span: 12, placeholder: '校正系数', },
    {type: 'textarea', label: '备注: ', prop: 'remark', rows: 3, span: 24, placeholder: '备注', }
  ],
  buttonsAttrs: {
    // align: 'center'
  }
});

// 表单验证规则
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入危险化学品名称', trigger: 'blur'}],
  safetyNo: [{ required: true, message: '请输入危规号', trigger: 'blur'}],
  isToxic: [{ required: true, message: '请选择是否是剧毒化学品', trigger: 'change'}],
  device: [{ required: true, message: '请输入所处装置（或区域）', trigger: 'blur'}],
  onlineStore: [{ required: true, message: '请输入在线存在量（吨）', trigger: 'blur'}],
  critValue: [{ required: true, message: '请输入临界值（吨）', trigger: 'blur'}],
  betaValue: [{ required: true, message: '请输入校正系数', trigger: 'blur'}],
});

// 表单验证规则
const addMHBIFormRef = ref<FormInstance>();

const handleSubmit = async () => {
  const valid = await addMHBIFormRef.value?.validateForm();
  console.log(valid); //true or false
  if (valid) {
    console.log('执行新增操作！');
    let actionMethod = materialOptCase.value.operaCase==='add' ? 'insertMajorHazardMaterial': 'updateMajorHazardMaterial';

    global.$api[actionMethod](Object.assign({}, form.value.model, {hazardInfoId: optCase.value.hazardInfoId, hazardCode: optCase.value.hazardCode}))
        .then(({ data }) => {
          if (data.status === 'OK') {
            emit('flush', {});
          }
    });
  }
}

const handleReset = () => {
  console.log('危险物质form reset');
  nextTick(() => {
    addMHBIFormRef.value?.resetFields();
  })
}


defineExpose({
  handleSubmit,
  handleReset
})

onMounted(() => {
  if (materialOptCase.value.operaCase==='view' || materialOptCase.value.operaCase==='edit') {
    global.$api.getMajorHazardMaterialById(materialOptCase.value).then(({ data }) => {
      if (data.status === 'OK') {
        form.value.model = data.data;
      }
    })
  }
})
</script>

<style scoped>

</style>
